import {
    Form,
    Outlet,
    redirect,
    useLoaderData,
    useRevalidator,
} from "@remix-run/react";
import { useEffect, useMemo, useState } from "react";
import { Textarea } from "~/components/ui/textarea";
import { Button } from "~/components/ui/button";
import { Label } from "~/components/ui/label";
import { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/cloudflare";
import {
    createComfyOneAPI,
    T2I_WORKFLOW_ID,
    TOKEN,
} from "~/services/onethingAI";
import AuthImage from "~/components/ui/auth-image";
import { TaskData } from "~/models";
import { Card } from "~/components/ui/card";

// type AspectRatio = "1:1" | "3:4" | "4:3";

export const loader = async ({ request }: LoaderFunctionArgs) => {
    const url = new URL(request.url);
    const taskId = url.searchParams.get("taskId");
    console.log("taskId: " + taskId);
    if (!taskId) {
        return {};
    }
    const api = createComfyOneAPI();
    const resp = await api.getTaskStatus(taskId);

    return Response.json({ task: resp.data, taskId });
};

export const action = async ({ request }: ActionFunctionArgs) => {
    const formData = await request.formData();
    const prompt = formData.get("prompt");

    const api = createComfyOneAPI();

    try {
        const taskResponse = await api.createTask({
            workflow_id: T2I_WORKFLOW_ID,
            inputs: [
                {
                    id: 8,
                    params: {
                        String: prompt,
                    },
                },
            ],
            free_cache: false,
        });

        console.log({ prompt, taskResponse });

        return redirect(`/features/t2i?taskId=${taskResponse.data.taskId}`);
    } catch (error) {
        console.error("创建任务失败:", error);
        throw error;
    }
};

type LoaderData = {
    task: TaskData;
    taskId: string;
};

export default function TextToImagePage() {
    // const [selectedRatio, setSelectedRatio] = useState<AspectRatio>("1:1");

    // const aspectRatios: AspectRatio[] = ["1:1", "3:4", "4:3"];

    const { task, taskId } = useLoaderData<LoaderData>();

    const [images, setImages] = useState<string[]>([]);
    const revalidator = useRevalidator();

    const isDone = task != null;
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [prompt, setPrompt] = useState("");

    console.log({ task });

    const handleSubmit = () => {
        setIsSubmitting(true);
    };

    useEffect(() => {
        if (!task) {
            return;
        }

        const revalidate = () => {
            if (revalidator.state === "idle") {
                revalidator.revalidate();
            }
        };

        if (task.status === "finished") {
            setIsSubmitting(false);
            setImages(task.images || []);
        } else {
            setIsSubmitting(true);
            setImages([]);
            const timer = setTimeout(revalidate, 5000);
            return () => clearTimeout(timer);
        }
    }, [task, revalidator]);

    // 使用 useMemo 优化 headers
    const imgHeaders = useMemo(
        () => ({
            Authorization: `Bearer ${TOKEN}`,
        }),
        []
    );

    const isValid = prompt.length > 0;

    return (
        <section className="flex">
            <div className="flex flex-col space-y-4 p-4 w-1/3">
                <Form id="t2i-form" method="post" onSubmit={handleSubmit}>
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label>房间描述</Label>
                            <Textarea
                                name="prompt"
                                value={prompt}
                                onChange={(e) => setPrompt(e.target.value)}
                                placeholder="请输入详细的房间描述，例如：一个现代简约风格的客厅，白色墙面，原木地板，大面积落地窗，灰色布艺沙发..."
                                className="min-h-[200px]"
                            />
                        </div>
                        <div className="space-y-4">
                            {/* <div className="space-y-2">
                                <Label>图片尺寸</Label>
                                <div className="flex gap-4">
                                    {aspectRatios.map((ratio) => (
                                        <Button
                                            key={ratio}
                                            variant="outline"
                                            className={`flex-1 ${
                                                selectedRatio === ratio
                                                    ? "bg-black text-white hover:bg-black/90"
                                                    : "hover:bg-gray-100"
                                            }`}
                                            onClick={() =>
                                                setSelectedRatio(ratio)
                                            }
                                        >
                                            {ratio}
                                        </Button>
                                    ))}
                                </div>
                            </div> */}
                            <div className="flex flex-col items-start space-y-2">
                                <Label>单次生成张数</Label>
                                <div className="rounded-md bg-black px-4 py-2 text-sm text-white">
                                    4张
                                </div>
                            </div>
                        </div>
                        <Button
                            type="submit"
                            className="w-full h-12"
                            disabled={isSubmitting || !isValid}
                        >
                            {isSubmitting ? "生成中..." : "生成设计图"}
                        </Button>
                    </div>
                </Form>
            </div>

            {images.length > 0 ? (
                <div className="flex-1 grid grid-cols-2 gap-4 p-4 max-h-screen ">
                    {images.map((image, index) => (
                        <Card
                            key={`${taskId}-${index}`}
                            className="overflow-hidden"
                        >
                            <AuthImage
                                headers={imgHeaders}
                                src={image}
                                alt={`生成的设计图 ${index + 1}`}
                                className="object-cover"
                            />
                        </Card>
                    ))}
                </div>
            ) : isDone ? (
                <div className="flex flex-col flex-1 justify-center items-center text-xl">
                    <div>图片生成中，请稍候...</div>
                    <div className="text-sm text-gray-500">
                        （预计需要3-5分钟）
                    </div>
                </div>
            ) : (
                <div className="flex flex-col flex-1 justify-center items-center text-xl">
                    <div>您尚未生成作品</div>
                </div>
            )}
        </section>
    );
}
